<template>
  <Form.Item :label="titleLabel" class="database">
    <Select v-model:value="currentDbIndex" @change="OnChangeServer">
      <Select.Option v-for="(item, index) of servers" :value="item.value">{{ item.text }}</Select.Option>
    </Select>
    <Select v-model:value="currentSchema" @change="OnChangeSchema">
      <Select.Option v-for="(item, index) of schemas" :value="item.value">{{ item.text }}</Select.Option>
    </Select>
  </Form.Item>
</template>

<script setup>
  import { ref, inject, onMounted } from 'vue';
  import { Form, Select } from 'ant-design-vue';

  const props = defineProps({
    igSqlite: {
      type: Boolean,
      default: false
    },
    dbIndex: {
      type: [String, Number],
      default: '0'
    },
    schema: {
      type: String
    },
    titleLabel: {
      type: String,
      default: '数据库'
    },
    inline: {
      type: Boolean,
      default: null
    },
    modelValue: Object
  });

  const $http = inject('$http');
  const $emits = defineEmits(['update:modelValue', 'change']);

  const servers = ref([]);
  const schemas = ref([]);

  const currentDbIndex = ref('0');
  const currentSchema = ref('');

  function OnChangeServer(dbIndex) {
    currentDbIndex.value = dbIndex;

    let dbType = servers.value[dbIndex].type;

    $http.get(`/api/db/${currentDbIndex.value}/dbs`).then(res => {
      schemas.value = (res.datas || []).map(r => {
        return { text: r.Name, value: r.Name };
      });

      currentSchema.value = schemas.value.find(s => s.value == props.schema) ? props.schema : schemas.value[0].value;

      OnChangeSchema();
    });
  }

  function OnChangeSchema() {
    let dbType = servers.value[currentDbIndex.value].type;

    $emits('change', {
      dbIndex: currentDbIndex.value,
      schema: currentSchema.value,
      type: dbType
    });
  }

  function Initialize() {
    $http.get('/api/db/servers').then(res => {
      let index = 0;

      let dbs = res;

      if (props.igSqlite) {
        dbs = dbs.filter(s => s.type != 'sqlite');
      }

      servers.value.push(
        ...dbs.map(r => {
          return { text: r.display, value: (index++).toString(), type: r.type };
        })
      );

      OnChangeServer((props.dbIndex || 0).toString());
    });
  }

  onMounted(() => {
    Initialize();
  });
</script>
<style lang="less">
  .database {
    margin-bottom: 0;
    flex-flow: row nowrap;

    .ant-form-item-control-input-content {
      display: flex;
      flex-flow: row nowrap;

      > div {
        margin-right: 10px;

        &:last-of-type {
          margin-right: 0px;
        }
      }
    }
  }
</style>
